package com.hczt.xhminiapp.adminapi.modules.system.service;

import com.hczt.xhminiapp.db.entity.Dict;
import com.hczt.xhminiapp.db.repository.DictRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 红创-马海强
 * @date 2019-03-13 15:52
 * @description
 */
@Service
public class DictService {

    @Autowired
    private DictRepository dictRepository;

    /**
     * 字段数据树结构
     * @return
     */
    public List<Dict> findDictTree() {
        List<Dict> dictList = dictRepository.findAll();
        return dictToTree(null, dictList);
    }

    private List<Dict> dictToTree(Dict parent, List<Dict> dictList) {
        int parentId = parent != null ? parent.getId(): 0;
        List<Dict> children = dictList.stream().filter(o -> o.getParentId() == parentId).collect(Collectors.toList());
        if(null != parent) {
            parent.setChildren(children);
        }
        children.forEach(o -> dictToTree(o, dictList));
        return children;
    }
}
